package com.tgb.lk.ui;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.Arrays;
import java.util.List;

import com.tgb.lk.table.Log;
import com.tgb.lk.table.MysqlTableManager;
import com.tgb.lk.table.TableColumn;
import com.tgb.lk.table.TableConfig;
import com.tgb.lk.table.OracleTableManager;
import com.tgb.lk.table.SQLTableManager;
import com.tgb.lk.table.Table;
import com.tgb.lk.table.TableManager;
import com.tgb.lk.util.AppConstants;
import com.tgb.lk.util.ExcelUtil;
import com.tgb.lk.util.FileUtil;

class MakeTableDoc extends Thread {

	public MakeTableDoc() {
		flag = 0;
	}

	@Override
    public void run() {
		String tables[] = TableConfig.getInstance().getTableList();
		Table table = null;
		String path = "";
		List<TableColumn>[] columnLists = new List[tables.length];
		String[] columnNames = new String[tables.length];
		if (tables != null && tables.length > 0) {
			for (int i = 0; i < tables.length && flag == 0; i++) {
				TableManager t = null;
				int data_type = TableConfig.getInstance().getDataBaseType();
				if (data_type == AppConstants.DB_SQLSERVER) {
					t = SQLTableManager.getInstance();
				} else if (data_type == AppConstants.DB_ORACLE) {
					t = OracleTableManager.getInstance();
				} else {
					t = MysqlTableManager.getInstance();
				}
				table = t.getTableInfo(tables[i]);
				columnLists[i] = Arrays.asList(table.getColumns());
				columnNames[i] = table.getName();
			}
			FileOutputStream out = null;
			path = AppConstants.BASE_PATH + "dest-excel/tables.xls";
			FileUtil.makeFilePath(path);
			try {
				out = new FileOutputStream(path);
			} catch (FileNotFoundException e) {
				Log.log(e);
				e.printStackTrace();
			}
			ExcelUtil util = new ExcelUtil(TableColumn.class);
			util.exportExcel(columnLists, columnNames, out);

			Log.log("生成数据表文档成功,生成文档位置:" + path, 3);
		} else {
			Log.log("根据数据表文档时发生错误,请选择表后再试一次.", 3);
		}
	}

	public void setFlag(int f) {
		flag = f;
	}

	int flag;
}